/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

(function() {

    var socket;
    var currentUserData;

    $(document).on('socketActivated', function(event) {
        socket = event.socket;
        currentUserData = event.currentUserData;
        initializeEvents();
    });

    function initializeEvents() {

        $(document).on('newMessageSent', sendMessage);
        $(document).on('replyMessageSent', sendMessage);

        $(document).on('messageOpened', function(event) {
            //  decrement the message count
            var inboxCount = $('.inboxCount').html();
            if (inboxCount > 0) {
                inboxCount--;
            }

            $('.inboxCount').html(inboxCount);
            $('.msgCount').html(inboxCount);

            //  this function should also represent the event for message seen
            if (typeof event.messageData === 'undefined') {
                //  error: the message data object should not be undefined
                return;
            }

            $('#current-selected-message').html(event.messageData.id);
            //  TODO: add socket capabilities for seen here
        });

        socket.on('messageRecieved', function(data) {
            var selectedConversation = $('#current-selected-message').html();
            
            console.log(selectedConversation);
            console.log(data.id);
            if (selectedConversation == data.id) {
                //  remove animator classes
                $('.new-socket-message').removeClass('new-socket-message');

                //  the same conversation is currently opened in the users view,
                //  add the message view to the view
                var replyCount = $('.messagesOne > li').length;
                if (replyCount != 0) {
                    $(messageObjectToHTML(data)).insertAfter(".messagesOne li:nth-child(" + replyCount + ")");
                    $('.messagesOne').animate({scrollTop: $('.messagesOne')[0].scrollHeight}, 1000);
                } else {
                    $('.messagesOne').html(messageObjectToHTML(data));
                }

                //  apply animation to newly recieved message
                $('.new-socket-message > .messageArea').css('background-color', '#0E84CC');
                $('.new-socket-message > .messageArea').animate({
                    backgroundColor: '#FFF'
                }, 1000);

            } else {
                //  reload the message list/inbox
                $(".loadMsgList").html(null);
                $(".more").remove();
                $(".load_m").show();
                setTimeout(function() {
                    get_loadMsg("load", "loadMsg", "", "", function() {

                        //  reassign the selected conversation
                        if (typeof selectedConversation !== 'undefined') {
                            $('.viewMsg').removeClass('active_vMsg');
                            $('#msg_' + selectedConversation).addClass('active_vMsg');
                        }

                        appendMessageCount();
                    });
                });

            }
        });
    }

    function sendMessage(event) {
        if (!event.messageData) {
            //  message data missing, cannot continue message push
            return;
        }

        var sendTo;
        
        if (event.messageData.addPeopleConversation) {
            sendTo = event.messageData.addPeopleConversation.split(',');
        } else if (event.messageData.userListID) {
            sendTo = event.messageData.userListID.split(',');
        }
        
        var data = event.messageData;

        //  remove the id of the sender from the sendTo variable if it is\
        //  existing there
        var ownIdIndex = sendTo.indexOf(currentUserData.id);
        if (ownIdIndex > -1) {
            sendTo.splice(ownIdIndex, 1);
        }

        console.log(sendTo);

        data.senderData = currentUserData;
        data.sendTo = sendTo;
        socket.emit('message', data);
    }

    function appendMessageCount() {
//        var previousMessageCount = parseInt($('.msgCount').html());

        //  not needed anymore, kept for reference, this will be removed later
//        if (typeof $('.inboxCount').html() !== 'undefined') {
//            $('.msgCount').html($('.inboxCount').html());
//        } else {
//            $('.msgCount').html(previousMessageCount + 1);
//        }
//
//        $('.msgCount').html($('.inboxCount').html());
        $('.msgCount').effect('shake', {
            direction: 'up',
            distance: 5
        });
    }

    function messageObjectToHTML(messageData) {

        var html = '<li class="by_me new-socket-message" data-by="' + messageData.id + '">';
        html += '<a href="#" title="">' + messageData.senderData.image + '</a>';
        html += '   <div class="messageArea">';
        html += '       <span class="aro"></span>';
        html += '       <div class="infoRow">';
        html += '           <span class="name"><strong>' + messageData.senderData.displayName + '</strong> says:</span>';
        html += '           <span class="time timeago" title="' + COMMON_FUNCTIONS.getCurrentDate() + '"></span>';
        html += '       </div>';
        html += '       <label class="updateMsg">';
        html += '           ' + msg_nl2br(messageData.msg);
        //  TODO: put attachment image here
        html += '       </label>';
        html += '       <br>';
        html += '   </div>';
        html += '</li>';

        return html;

    }

    function msg_nl2br(varTest) {
        //  Copied from message_functions.js
        return varTest.replace(/&lt;br&gt;/g, "<br>").replace(/&lt;a&gt;/g, "<a>").replace(/&lt;\/\a&gt;/g, "</a>");
    }

})();